#include "version.h"

version::version()
{

}

void version::checkVersion(point upperLeft, point upperRight, point lowerLeft, int pixelProportion, QImage* img)
{
    int dimension = abs(upperRight.getColumn()/pixelProportion-upperLeft.getColumn()/pixelProportion)+6;
    int version = (dimension-14)/4;
    if (version > 6)
        version = checkExactVersion(upperRight, lowerLeft, pixelProportion, img);
    versionINFO = version;
    converter c;
    log->addLog("\nVERSAO = " + c.intToString(getVersionINFO()));
}

int version::checkExactVersion(point upperRight, point lowerLeft, int pixelProportion, QImage* img)
{
    int version = 0;
    int counter = 17;

    pixel p;

    for (int row = 0; row < 6*pixelProportion; row += pixelProportion)
    {
        for (int col = 0; col < 3*pixelProportion; col += pixelProportion)
        {
            if (p.isPixelBlack(upperRight.getRow()-(3*pixelProportion)+row,upperRight.getColumn()-(7*pixelProportion)+col,img))
                version += 1 << counter;
            counter--;
            p.paintPixel(upperRight.getRow()-(3*pixelProportion)+row, upperRight.getColumn()-(7*pixelProportion)+col, pixelProportion, qRgb(32,255,200), img);
        }
    }

    int version2 = 0;
    counter = 17;

    for (int col = 0; col < 6*pixelProportion; col += pixelProportion)
    {
        for (int row = 0; row < 3*pixelProportion; row += pixelProportion)
        {
            if (p.isPixelBlack(lowerLeft.getRow()-(7*pixelProportion)+row, lowerLeft.getColumn()-(3*pixelProportion)+col, img))
                version2 += 1 << counter;
            counter--;
            p.paintPixel(lowerLeft.getRow()-(7*pixelProportion)+row, lowerLeft.getColumn()-(3*pixelProportion)+col, pixelProportion, qRgb(32,255,200), img);
        }
    }

    if (version != version2) // assert version number
        version = 0;

    switch (version) {
        case VERSION_7:
            return 7;
            break;
        case VERSION_8:
            return 8;
            break;
        case VERSION_9:
            return 9;
            break;
        case VERSION_10:
            return 10;
            break;
        case VERSION_11:
            return 11;
            break;
        case VERSION_12:
            return 12;
            break;
        case VERSION_13:
            return 13;
            break;
        default:
            return 0;
            break;
    }
}

void version::setCanvas(canvas *log)
{
    this->log = log;
}

int version::getVersionINFO()
{
    return this->versionINFO;
}
